<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Constants\OperatorLogConstants;
use App\CustHub\Model\ChOperationLog;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;

class ChOperationLogMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChOperationLog::class;
    }


    public function getLogPageList(array $params): array
    {
        $pageSize = $params['pageSize'] ?? MineModel::PAGE_SIZE;

        $query = $this->model::query()
            ->with(['robots'=>function ($query) {
                $query->select(['id','nickname']);
            }]);

        $p = $this->handleSearch($query,$params)
            ->orderBy('created_at','desc')
            ->paginate((int)$pageSize);

        return $this->setPaginate($p);
    }

    public function handlePageItems(array $items,array $params): array
    {
        foreach ($items as $k=>$item){
            if($item['uid'] == $item['main_uid']){
                $items[$k]['operator'] = '主账号';
            }else{
                $items[$k]['operator'] = $item['user']['username'];
            }
            unset($item['user']);
        }
        return $items;
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        $query->where('main_uid',$params['main_uid']);
        $query->where('type',$params['type'] ?? OperatorLogConstants::NEW_CUSTOMER);

        if(!empty($params['robot_id'])){
            $robotId = $params['robot_id'];
            $query->whereHas('robots',function ($query) use ($robotId){
                $query->where('id',$robotId);
            });
        }

        if(!empty($params['scheme_id'])){
            $query->where('scheme_id',$params['scheme_id']);
        }

        if(!empty($params['name'])){
            $query->where('name','like','%'.$params['name'].'%');
        }
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $query->whereBetween('created_at', [$params['start_time'], $params['end_time']]);
        }


        return $query;
    }
}